package com.bsy.common.helper

import android.content.Context
import android.os.Environment
import com.bsy.common.R
import com.bsy.common.utils.getStringFromResource
import java.io.File
import java.math.BigDecimal
import java.math.RoundingMode


/**
 * Created by Sincerity on 2023/4/14.
 * Copyright
 * 描述：
 */
object CacheUtils {
    //获取缓存大小，包括内部缓存和外部缓存
    fun getCacheSize(context: Context): String {
        val internalCacheSize = getFolderSize(context.cacheDir)
        val externalCacheSize = if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED)
            getFolderSize(context.externalCacheDir)
        else
            0L
        val totalCacheSize = internalCacheSize + externalCacheSize
        return formatFileSize(totalCacheSize)
    }

    //清除缓存，包括内部缓存和外部缓存
    fun clearCache(context: Context) {
        deleteFolder(context.cacheDir)
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            deleteFolder(context.externalCacheDir)
        }
    }

    //获取文件夹大小，递归遍历所有文件
    private fun getFolderSize(file: File?): Long {
        var size = 0L
        file?.let {
            if (it.isDirectory) {
                it.listFiles()?.forEach { subFile ->
                    size += getFolderSize(subFile)
                }
            } else {
                size += it.length()
            }
        }
        return size
    }

    //删除文件夹，递归删除所有文件
    private fun deleteFolder(file: File?) {
        file?.let {
            if (it.isDirectory) {
                it.listFiles()?.forEach { subFile ->
                    deleteFolder(subFile)
                }
            } else {
                it.delete()
            }
        }
    }

    //格式化文件大小，根据不同的单位显示
    private fun formatFileSize(size: Long): String {
        //定义一个数组存储单位
        val units = arrayOf("K", "M", "G")
        //定义一个变量存储转换后的大小
        var result = BigDecimal(size.toDouble() / 1024).setScale(2, RoundingMode.HALF_UP).toDouble()
        //定义一个变量存储单位的索引
        var index = 0
        //循环判断是否需要继续转换
        while (result >= 1024 && index < units.size) {
            //将结果除以1024，保留两位小数
            result = BigDecimal(result / 1024).setScale(2, RoundingMode.HALF_UP).toDouble()
            //将索引加一
            index++
        }
        //格式化0显示问题
        if (result == 0.0) {
            return getStringFromResource(R.string.lib_resources_text_cache_size)
        }
        //返回结果和单位拼接的字符串
        return "$result${units[index]}"
    }
}